<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\exception\LogicException;
use app\exam\model\admin\PaperShareConfig as PaperShareConfigModel;
use app\user\model\user\Account;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * Class PaperConfig
 *
 * @package app\exam\logic\admin
 */
class PaperShareConfig extends PaperShareConfigModel
{

    /**
     * 设置
     *
     * @param int   $paperId
     * @param array $configData
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveConfig(int $paperId, array $configData)
    {
        $data = $this->where('paper_id', $paperId)
            ->find();
        if (!$data) {
            $saved = [
                'paper_id' => $paperId,
                'cnf_data' => $configData
            ];

            $ret = $this->create($saved);
        } else {
            $data->cnf_data = $configData;
            $ret            = $data->save();
        }

        if (!$ret) {
            throw new LogicException('设置失败');
        }
    }

    /**
     * 获取配置
     *
     * @param int $paperId
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get(int $paperId)
    {
        $data    = $this->where('paper_id', $paperId)
            ->find();
        $cnfData = [];
        if ($data) {
            $cnfData = $data->cnf_data;
            // 获取用户信息
            if ($cnfData && isset($cnfData['user'])) {
                $user                 = $cnfData['user'] ?: [];
                $cnfData['user_list'] = Account::whereIn('id', $user)->field(['id' => 'value', 'nick_name', 'phone'])->select()->each(function ($item) {
                    $phone = '';
                    if ($item->phone) {
                        $phone = '（' . $item->phone . '）';
                    }
                    $item->title = $item->nick_name . $phone;
                });;
            }
        }

        return $cnfData;
    }
}